package com.asiainfo.cms.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.asiainfo.cms.common.constant.CacheConstant;
import com.asiainfo.cms.common.constant.UserConstants;
import com.asiainfo.cms.common.exception.BizException;
import com.asiainfo.cms.system.entity.SysConfig;
import com.asiainfo.cms.system.mapper.SysConfigMapper;
import com.asiainfo.cms.system.service.ISysConfigService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * 参数配置 服务层实现
 *
 * @author ruoyi
 */
@Service
public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig> implements ISysConfigService {
    @Autowired
    private SysConfigMapper configMapper;

    /**
     * 项目启动时，初始化参数到缓存
     */
    @PostConstruct
    public void init() {
        loadingConfigCache();
    }

    /**
     * 查询参数配置信息
     *
     * @param configId 参数配置ID
     * @return 参数配置信息
     */
    @Override
    public SysConfig selectConfigById(Long configId) {
        return configMapper.selectById(configId);
    }

    /**
     * 根据键名查询参数配置信息
     *
     * @param configKey 参数key
     * @return 参数键值
     */
    @Override
    public String selectConfigByKey(String configKey) {
        SysConfig config = new SysConfig();
        config.setConfigKey(configKey);
        QueryWrapper<SysConfig> wrapper = new QueryWrapper<>();
        wrapper.eq("config_key", configKey);
        SysConfig retConfig = configMapper.selectOne(wrapper);
        if (ObjectUtil.isNotEmpty(retConfig)) {
            return retConfig.getConfigValue();
        }
        return StringUtils.EMPTY;
    }

    /**
     * 获取验证码开关
     *
     * @return true开启，false关闭
     */
    @Override
    public boolean selectCaptchaOnOff() {
        String captchaOnOff = selectConfigByKey("sys.account.captchaOnOff");
        if (StringUtils.isEmpty(captchaOnOff)) {
            return true;
        }
        return Boolean.valueOf(captchaOnOff);
    }

    /**
     * 查询参数配置列表
     *
     * @param config 参数配置信息
     * @return 参数配置集合
     */
    @Override
    public Page<SysConfig> selectConfigList(Page page, SysConfig config) {
        QueryWrapper<SysConfig> wrapper = new QueryWrapper();

        if (ObjectUtil.isNotEmpty(config.getConfigId())) {
            wrapper.eq("config_id", config.getConfigId());
        }
        if (ObjectUtil.isNotEmpty(config.getConfigName())) {
            wrapper.like("config_name", config.getConfigName());
        }
        if (ObjectUtil.isNotEmpty(config.getConfigKey())) {
            wrapper.like("config_key", config.getConfigKey());
        }
        if (ObjectUtil.isNotEmpty(config.getConfigType())) {
            wrapper.eq("config_type", config.getConfigType());
        }

//        String strEnd= DateUtil.format(config.getEndTime(), DatePattern.NORM_DATETIME_PATTERN);
//        String start = DateUtil.format(config.getStartTime(),DatePattern.NORM_DATETIME_PATTERN);
//        wrapper.apply("UNIX_TIMESTAMP(create_time) >= UNIX_TIMESTAMP('" + start + "')");
//        wrapper.apply("UNIX_TIMESTAMP(create_time) < UNIX_TIMESTAMP('" + strEnd + "')");

        return configMapper.selectPage(page, wrapper);
    }

    /**
     * 新增参数配置
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public int insertConfig(SysConfig config) {
        return configMapper.insert(config);
    }

    /**
     * 修改参数配置
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public int updateConfig(SysConfig config) {
        return configMapper.updateById(config);
    }

    /**
     * 批量删除参数信息
     *
     * @param configIds 需要删除的参数ID
     */
    @Override
    public void deleteConfigByIds(Long[] configIds) {
        for (Long configId : configIds) {
            SysConfig config = selectConfigById(configId);
            if (StringUtils.equals(UserConstants.YES, config.getConfigType())) {
                throw new BizException(String.format("内置参数【%1$s】不能删除 ", config.getConfigKey()));
            }
            configMapper.deleteById(configId);
        }
    }

    /**
     * 加载参数缓存数据
     */
    @Override
    public void loadingConfigCache() {

        List<SysConfig> configsList = configMapper.selectList(new QueryWrapper<>());
    }

    /**
     * 清空参数缓存数据
     */
    @Override
    public void clearConfigCache() {
//        Collection<String> keys = redisCache.keys(Constants.SYS_CONFIG_KEY + "*");
//        redisCache.deleteObject(keys);
    }

    /**
     * 重置参数缓存数据
     */
    @Override
    public void resetConfigCache() {
        clearConfigCache();
        loadingConfigCache();
    }

    /**
     * 校验参数键名是否唯一
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public String checkConfigKeyUnique(SysConfig config) {
        Long configId = ObjectUtil.isNull(config.getConfigId()) ? -1L : config.getConfigId();
        QueryWrapper<SysConfig> wrapper = new QueryWrapper<>();
        wrapper.eq("config_key", config.getConfigKey());
        SysConfig info = configMapper.selectOne(wrapper);
        if (ObjectUtil.isNotNull(info) && info.getConfigId().longValue() != configId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    private String getCacheKey(String configKey) {
        return CacheConstant.SYS_CONFIG_KEY + configKey;
    }
}
